using System;
using System.Collections.Generic;
using System.Linq;
using Urs.Core.Data;
using Urs.Data.Domain.Common;
using Urs.Data.Domain.Users;
using Urs.Data.Domain.Configuration;
using Urs.Services.Directory;

namespace Urs.Services.Common
{
    public partial class AddressService : IAddressService
    {
        #region Fields

        private readonly IRepository<Address> _addressRepository;
        private readonly AddressSettings _addressSettings;
        private readonly IAreaService _areaService;
        private readonly IRepository<UserAddressMapping> _userAddressMappingRepository;
        #endregion

        #region Ctor

        public AddressService(IRepository<Address> addressRepository,
            AddressSettings addressSettings,
            IAreaService areaService,
            IRepository<UserAddressMapping> userAddressMappingRepository)
        {
            this._addressRepository = addressRepository;
            this._addressSettings = addressSettings;
            this._areaService = areaService;
            this._userAddressMappingRepository = userAddressMappingRepository;
        }

        #endregion

        #region Shipping Address

        public virtual void DeleteAddress(Address address)
        {
            if (address == null)
                throw new ArgumentNullException("address");

            _addressRepository.Delete(address);
        }

        public virtual Address GetAddressById(int addressId)
        {
            if (addressId == 0)
                return null;

            var address = _addressRepository.GetById(addressId);
            return address;
        }

        public virtual IList<Address> GetAddresses(int userId)
        {
            if (userId == 0)
                return new List<Address>();

            var query = (from p in _addressRepository.Table
                         join pc in _userAddressMappingRepository.Table on p.Id equals pc.AddressId
                         where userId == pc.UserId
                         select p);

            return query.ToList();
        }

        public virtual void InsertAddress(Address address)
        {
            if (address == null)
                throw new ArgumentNullException("address");

            address.CreateTime = DateTime.Now;
            _addressRepository.Insert(address);
        }

        public virtual void UpdateAddress(Address address)
        {
            if (address == null)
                throw new ArgumentNullException("address");

            _addressRepository.Update(address);
        }
        #endregion

    }
}